﻿namespace Manhua2.Pages
{
    using Manhua2.Common;
    using Manhua2.DataModel;
    using Manhua2.Helper;
    using Manhua2.Provider;
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;

    /// <summary>
    /// 基本页，提供大多数应用程序通用的特性。
    /// </summary>
    public sealed partial class ComicDirectoryPage : Manhua2.Controls.LayoutAwarePage
    {
        private ComicItem comic;

        public ComicDirectoryPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            this.DefaultViewModel["DownloadMode"] = Visibility.Collapsed;
            this.DefaultViewModel["Loading"] = Visibility.Collapsed;

            string error = null;

            try
            {
                if (navigationParameter == null) this.Frame.Navigate(typeof(MainPage));
                int comicId = (int)navigationParameter;
                using (ModelContext context = new ModelContext())
                {
                    comic = await context.GetComicAsync(comicId);
                    if (comic == null)
                        throw new ArgumentException(Global.Loader.GetString("DbError"));

                    var favorite = await context.GetFavoriteAsync(comicId);
                    this.btnFavorite.Tag = favorite == null ? "添加收藏" : "取消收藏";

                    var chapters = await context.QueryChaptersAsync(comicId);

                    this.DefaultViewModel["ComicTitle"] = comic.ComicTitle;
                    this.DefaultViewModel["Author"] = comic.Author;
                    this.DefaultViewModel["Cover"] = comic.Cover;
                    this.DefaultViewModel["Chapters"] = chapters;
                }
            }
            catch(Exception ex)
            {
                error = ex.Message;
            }

            await MethodHelper.ShowMessageDialogNotEmpty(error);
        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。值必须符合
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        /// <param name="pageState">要使用可序列化状态填充的空字典。</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void GridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem != null)
            {
                var item = (Chapter)e.ClickedItem;
                this.Frame.Navigate(typeof(ViewPageNew), item.ChapterId);
            }
        }

        private void btnHome_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(MainPage));
        }

        /// <summary>
        /// 添加或取消收藏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnFavorite_Click(object sender, RoutedEventArgs e)
        {
            if (this.comic == null) return;

            string error = null;

            try
            {
                using (ModelContext context = new ModelContext())
                {
                    if ((string)this.btnFavorite.Tag == "添加收藏")
                    {
                        await context.SaveFavoriteAsync(this.comic.Comic.Id);
                        await MethodHelper.ShowMessageDialog(Global.Loader.GetString("FavoriteSuccess"), Global.InformationDialogTitle);
                        this.btnFavorite.Tag = "取消收藏";
                    }
                    else
                    {
                        await context.DelteFavoriteAsync(this.comic.Comic.Id);
                        await MethodHelper.ShowMessageDialog("取消成功", Global.InformationDialogTitle);
                        this.btnFavorite.Tag = "添加收藏";
                    }
                }
            }
            catch(Exception ex)
            {
                error = ex.Message;
            }

            await MethodHelper.ShowMessageDialogNotEmpty(error);
        }

        private async void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            if (this.comic == null) return;

            string error = null;

            try
            {
                this.DefaultViewModel["Loading"] = Visibility.Visible;

                await DownloadComicDirectory(this.comic.Comic.Id);

                using (ModelContext context = new ModelContext())
                {
                    var chapters = await context.QueryChaptersAsync(this.comic.Comic.Id);
                    this.DefaultViewModel["Chapters"] = chapters;
                }
            }
            catch(Exception ex)
            {
                error = ex.Message;
            }

            this.DefaultViewModel["Loading"] = Visibility.Collapsed; ;

            await MethodHelper.ShowMessageDialogNotEmpty(error);
        }

        private async void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            if (this.gridView.SelectedItems.Count == 0)
            {
                await MethodHelper.ShowMessageDialog("请选择需要下载的章节！", "提示");
                return;
            }

            Task command = MethodHelper.ShowMessageDialog("正在准备下载数据, 该过程可能会比较缓慢, 请耐心等待(关闭此窗口并等待下一条提示通知)...", "提示");

            List<Task> tasks = new List<Task>();
            foreach (Chapter chapter in this.gridView.SelectedItems)
            {
                DownloadItem item = await DownloadManager.CreateDownloadItemAsync(chapter.ChapterId);
                try
                {
                    await DownloadManager.AddToDownloads(item);
                }
                catch
                { 
                }

                tasks.Add(DownloadManager.StartDownload(item));
            }

            await command;
            await MethodHelper.ShowMessageDialog("已经添加到下载列表中, 下载完成后请前往\"下载\"文件夹中查看", "提示");
            await Task.WhenAll(tasks);
        }

        private void btnSelectAll_Click(object sender, RoutedEventArgs e)
        {
            if ((string)this.btnSelectAll.Tag == "全选")
            {
                this.gridView.SelectAll();
                this.btnSelectAll.Tag = "取消全选";
            }
            else
            {
                this.gridView.SelectedItems.Clear();
                this.btnSelectAll.Tag = "全选";
            }
        }

        private void btnDownloadMode_Click(object sender, RoutedEventArgs e)
        {
            if ((string)this.btnDownloadMode.Tag == "开启下载模式")
            {
                this.DefaultViewModel["DownloadMode"] = Visibility.Visible;
                this.gridView.IsItemClickEnabled = false;
                this.btnDownloadMode.Tag = "关闭下载模式";
            }
            else
            {
                this.DefaultViewModel["DownloadMode"] = Visibility.Collapsed;
                this.gridView.SelectedItems.Clear();
                this.gridView.IsItemClickEnabled = true;
                this.btnDownloadMode.Tag = "开启下载模式";
            }
        }

        private static async Task DownloadComicDirectory(int comicId)
        {
            using (DbContext context = new DbContext())
            {
                var comic = await context.GetAsync<SQLiteTable.SQLiteComic>(comicId);
                IComicProvider provider = ComicProviderFactory.Create(comic.Provider);
                await provider.SaveChaptersAsync(comicId);
            }
        }
    }
}
